package com.cicoding.tcp.server;

import cn.hutool.extra.spring.SpringUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;

import com.alibaba.fastjson.TypeReference;
import com.alibaba.fastjson2.JSON;
import com.cicoding.entity.vo.LogBaseEpcInfo;
import com.cicoding.entity.vo.ResponseData;
import com.cicoding.service.Uf3sReaderService;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;

import com.fasterxml.jackson.databind.type.TypeFactory;

import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.util.concurrent.GlobalEventExecutor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.lang.reflect.Type;
import java.util.List;
import java.util.Objects;

/**
 * @author: zhouwenjie
 * @description: 服务端业务处理类
 * @create: 2020-04-03 14:13
 **/
@Slf4j
@Component
@ChannelHandler.Sharable
public class NettyServerHandler extends ChannelInboundHandlerAdapter {

    public static ChannelGroup clients = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);

    @Override
    public void channelActive(ChannelHandlerContext ctx) {
        clients.add(ctx.channel());
        System.out.println(ctx.channel().id().asLongText() + "连接成功, web客户端数量：" + clients.size() + "个");
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) {
        System.out.println(ctx.channel().id().asLongText() + "连接断开, 剩余web客户端数量：" + clients.size() + "个");
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) {
        String jsonString = msg.toString();
        try {
            if (jsonString.endsWith("$")) {
                jsonString = jsonString.substring(0, jsonString.length() - 1);
            }
            JSONObject jsonObject = JSONUtil.parseObj(jsonString);
            String code = jsonObject.getStr("code");

            if ("1001".equals(code)) {
                Type type = new TypeReference<ResponseData<LogBaseEpcInfo>>() {}.getType();
                ResponseData<LogBaseEpcInfo> serverResponse = JSON.parseObject(jsonString, type);

                List<LogBaseEpcInfo> serverResponseData = serverResponse.getData();
                for (LogBaseEpcInfo serverResponseDatum : serverResponseData) {
                    long timeMillis = System.currentTimeMillis();
                    String epc = serverResponseDatum.getEpc();
                    if (Uf3sReaderService.flage) {
                        Uf3sReaderService.cache.put(epc, timeMillis);
                        log.error("--首轮打印标签---- {} ", epc);
                    } else {
                        Uf3sReaderService.RFIDCache.put(epc, timeMillis);
                    }
                }
            }
        } catch (Exception e) {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            e.printStackTrace(new PrintStream(baos));
            log.error("tcp客户端---收到消息处理失败，源数据：{}  失败原因：{}", jsonString, baos.toString());
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        log.error("连接异常,异常信息：" + cause.getMessage());
        cause.printStackTrace();
    }

    public static void main(String[] args) {
        String test = "{\"code\":1001,\"data\":[{\"additionDataBytes\":\"\",\"additionDataHexStr\":\"\",\"antId\":1,\"bEpc\":\"4gAAAGmS\",\"epc\":\"E20000006992\",\"pc\":\"1800\",\"readTime\":1718088718727,\"rssi\":-59}],\"rtCode\":0}";
        Type type = new TypeReference<ResponseData<LogBaseEpcInfo>>() {}.getType();
        ResponseData<LogBaseEpcInfo> serverResponse = JSON.parseObject(test, type);
        List<LogBaseEpcInfo> serverResponseData = serverResponse.getData();
        for (LogBaseEpcInfo serverResponseDatum : serverResponseData) {
            System.out.println(serverResponseDatum);
        }
    }
}

